package com.whj.servicemap.remote;

/**
 * @Auther: wanghaijun
 * @Date: 2023/1/20 - 01 - 20 - 11:39 
 * @Description: com.whj.servicemap.remote
 */

import com.fasterxml.jackson.annotation.JsonFormat;
import com.whj.internalcommon.constant.AMapConfigConstant;
import com.whj.internalcommon.dto.ResponseResult;
import com.whj.internalcommon.response.TerminalResponse;
import com.whj.internalcommon.response.TrackResponse;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

/**
 * 调用高德创建轨迹id trid
 */

@Service
@Slf4j
public class TrackClient {
    @Value("${amap.key}")
    private String amapKey;

    @Value("${amap.sid}")
    private String amapSid;

    @Autowired
    private RestTemplate restTemplate;

    /**
     * 获取终端设备id
     *
     * @param tid
     * @return
     */
    public ResponseResult<TrackResponse> addTrack(String tid) {

        //?key=9edd7a0c343d993fc971ad2afda94dd5&sid=869338&tid=623209785&trname=测试轨迹
        StringBuilder url = new StringBuilder();
        url.append(AMapConfigConstant.TRACK_ADD_URL);
        url.append("?");
        url.append("key=" + amapKey);
        url.append("&");
        url.append("sid=" + amapSid);
        url.append("&");
        url.append("tid=" + tid);
        log.info(url.toString());

        ResponseEntity<String> forEntity = restTemplate.postForEntity(url.toString(), null, String.class);
        /**
         * 解析json
         * {
         *     "data": {
         *         "trname": "测试轨迹1",
         *         "trid": 80
         *     },
         *     "errcode": 10000,
         *     "errdetail": null,
         *     "errmsg": "OK"
         * }
         */
        String body = forEntity.getBody();
        JSONObject result = JSONObject.fromObject(body);
        JSONObject data = result.getJSONObject("data");
        String trname="";
        if(data.has("trname")){
            trname = data.getString("trname");
        }
        String trid = data.getString("trid");
        TrackResponse trackResponse = new TrackResponse();
        trackResponse.setTrid(trid);
        trackResponse.setTrname(trname);

        return ResponseResult.success(trackResponse);
    }
}
